package SwordOffer2;

import java.util.Stack;

public class day8_2 {
    /*
     * 1.创建函数reverseList()将两个字符串反转，并记录字符串长度len
     * 2.按长的字符串循环，不足的一个末尾补零，创建栈stack保存每一位结果sum=n1+n2+cur(进位)，循环结束判断，若进位为1，stack末尾添加1
     * 3.创建链表res逐个取出stack的值，返回res
     * */
    int len = 0;

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        Stack<Integer> stack = new Stack<>();
        ListNode tailer = new ListNode();
        ListNode res = tailer;
        ListNode list1 = reverseList(l1);
        int len1 = len;
        ListNode list2 = reverseList(l2);
        int len2 = len;
        ListNode listNode = new ListNode();
        int cur = 0;
        while (list1 != null || list2 != null) {
            int n1 = 0;
            int n2 = 0;
            int sum = 0;
            if (list1 != null) {
                n1 = list1.val;
                list1 = list1.next;
            }
            if (list2 != null) {
                n2 = list2.val;
                list2 = list2.next;
            }
            sum = n1 + n2 + cur;
            if (sum > 9) {
                cur = 1;
                stack.add(sum % 10);
            } else {
                cur = 0;
                stack.add(sum);
            }
        }
        if (cur == 1) {
            stack.add(1);
        }
        while (!stack.isEmpty()) {
            if (tailer.next == null) {
                ListNode node = new ListNode(stack.pop());
                tailer.next = node;
                tailer = tailer.next;
                tailer.next = node.next;
            }
        }
        return res.next;
    }

    public ListNode reverseList(ListNode head) {
        len = 0;
        ListNode pre = null;
        ListNode cur = head;
        while (cur != null) {
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
            len++;
        }
        return pre;
    }
}
